package io_nio;

import java.io.*;
import java.nio.CharBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;

public class ChannelDemo {
    public static void main(String[] args) {
        File file = new File("E:\\pp3\\effective-java\\src\\io_nio\\ChannelDemo.java");
        FileInputStream fis = null;
        FileOutputStream fos = null;
        FileChannel inChannel;
        FileChannel outChannel;
        try {
            fis = new FileInputStream(file);
            inChannel = fis.getChannel();//Channel对象都应该通过传统的节点流获取
            MappedByteBuffer buffer = inChannel.map(FileChannel.MapMode.READ_ONLY, 0, file.length());//全部映射到buffer
            fos = new FileOutputStream("E:/pp3/IO_Demo.txt");
            outChannel = fos.getChannel();
            outChannel.write(buffer);//把buffer里的全部写出
            buffer.clear();//写出后复原buffer
            Charset charset = Charset.forName("UTF-8");//解码器
            CharsetDecoder decoder = charset.newDecoder();
            CharBuffer charBuffer = decoder.decode(buffer);
            System.out.println(charBuffer);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e){
            e.printStackTrace();
        }finally {
            try {
                if (fis != null){
                    fis.close();
                }
                if (fos != null){
                    fos.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }

    }


}
